package com.zh.sharding.sale;

import com.alibaba.fastjson.JSON;
import com.zh.sharding.sale.entity.User;
import com.zh.sharding.sale.repository.UserDao;
import com.zh.sharding.sale.support.OperationHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhou
 * @date 2023/8/23
 */
@RestController
public class UserController {
    @Autowired
    private UserDao userDao;


    /*
    {
    "username": "小米手机",
    "phone": "100",
    }
     */
    @PostMapping("/user/add")
    public Long addUser(@RequestBody User form) throws Exception {
        OperationHelper.log("创建新user啦 addUser: form = "+ JSON.toJSONString(form));

        User user = new User(form.getUsername(), form.getPhone(),form.getCardNumber());

        userDao.insert(user);

        OperationHelper.log("新user的ID="+user.getId());
        return user.getId();
    }

    @GetMapping("/user/id/{id}")
    public User findUser(@PathVariable Long id) throws Exception {
        OperationHelper.log("查询user详情 findUser: ID = "+ id);
        User user = userDao.selectById(id);
        return user;
    }

    @GetMapping("/user/one/{username}")
    public User findUserByUsername(@PathVariable String username) throws Exception {
        OperationHelper.log("查询user详情 selectByUsername: username = "+ username);
        User user = userDao.selectByUsername(username);
        return user;
    }
}
